import path from 'node:path'
import process from 'node:process'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import autoImport from 'unplugin-auto-import/vite'
import components from 'unplugin-vue-components/vite'
import {loadEnv, type PluginOption} from 'vite'
import {createSvgIconsPlugin} from 'vite-plugin-svg-icons'
import VueDevTools from 'vite-plugin-vue-devtools'
import zh_hans from '../monaco/zh.json'
import nlsPlugin, {Languages} from '../monaco/nls.ts'
import compression from "vite-plugin-compression2";
import {fileURLToPath} from "node:url";
import {quasar, transformAssetUrls} from '@quasar/vite-plugin'
export default function createVitePlugins(mode: string, isBuild = false) {
    const viteEnv = loadEnv(mode, process.cwd())

    const vitePlugins: (PluginOption | PluginOption[])[] = [

        // https://github.com/unplugin/unplugin-auto-import
        autoImport({
            imports: [
                'vue',
                'vue-router',
                'pinia',
            ],
            dts: './src/types/auto-imports.d.ts',
        }),

        vue({
            template: {transformAssetUrls}
        }),
        // https://github.com/unplugin/unplugin-vue-components
        components({
            dirs: ['src/components'],
            include: [/\.vue$/, /\.vue\?vue/, /\.tsx$/],
            dts: './src/types/components.d.ts',
        }),

        vueJsx(),
        quasar({
            sassVariables: fileURLToPath(
                new URL('../src/styles/quasar-variables.sass', import.meta.url)
            )
        }),
        // https://github.com/vuejs/devtools-next
        viteEnv.VITE_OPEN_DEVTOOLS === 'true' && VueDevTools(),


        // https://github.com/vbenjs/vite-plugin-svg-icons
        createSvgIconsPlugin({
            iconDirs: [path.resolve(process.cwd(), 'src/assets/icons/')],
            symbolId: 'svg-[dir]-[name]',
            svgoOptions: isBuild,
        }),


        // https://github.com/nonzzz/vite-plugin-compression
        viteEnv.VITE_BUILD_COMPRESS?.split(',').includes('gzip') && compression(),
        viteEnv.VITE_BUILD_COMPRESS?.split(',').includes('brotli') && compression({
            exclude: [/\.(br)$/, /\.(gz)$/],
            algorithm: 'brotliCompress',
        }),
    ]


    if (isBuild) {
        vitePlugins.push(nlsPlugin({
            locale: Languages.zh_hans,
            localeData: zh_hans,
        }))
    }
    return vitePlugins
}
